package org.geekbang.projects.injection;

import org.eclipse.microprofile.config.spi.ConfigSource;
import org.geekbang.projects.config.ConfigurationComponentLoader;
import org.geekbang.projects.config.converter.MatchableConverter;
import org.geekbang.projects.injection.processor.ApplicationContextAware;

import java.util.List;
import java.util.stream.Collectors;

/**
* 优先级顺序   jndi > system（os） > properties
* @author : KangNing Hu
*/
public class EnvironmentComponentLoader implements ConfigurationComponentLoader , ApplicationContextAware {


	private static ApplicationContext APPLICATION_CONTEXT;

	@Override
	public List<ConfigSource> loaderConfigSources() {
		List<Object> config = APPLICATION_CONTEXT.getBeansByPrefix("config");
		if (config == null){
			return null;
		}
		return config.stream().filter(item -> item instanceof ConfigSource).map(item -> (ConfigSource)item).collect(Collectors.toList());
	}

	@Override
	public List<MatchableConverter> loaderConverters() {
		List<Object> config = APPLICATION_CONTEXT.getBeansByPrefix("converter");
		if (config == null){
			return null;
		}
		return config.stream().filter(item -> item instanceof MatchableConverter).map(item -> (MatchableConverter)item).collect(Collectors.toList());
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		APPLICATION_CONTEXT = applicationContext;
	}
}
